import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Button, Card, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import './index.css'
import request from '../../utils/request'
interface ValuesType {
	email: string,
	password: string
}
const Login: React.FC = () => {
	const [form] = Form.useForm()
	const [loading, setLoading] = useState(false)
	const navigate = useNavigate()
	const onFinish = async (values: ValuesType) => {
		setLoading(true)
		try {
			const res = await request.post('/api/v1/auth/login', { ...values })
			console.log(res)
			const { code, data } = res.data
			console.log(code, data)
			if (code === 200) {
				localStorage.setItem('userinfo', JSON.stringify(data.user))
				localStorage.setItem('token', data.token)
				message.success('登录成功')
				navigate('/')
			}
		} catch (error: any) {
			console.error('登录错误:', error)
			const errorMsg = error.response?.data?.message || '登录失败，请重试'
			message.error(errorMsg)
		} finally {
			setLoading(false)
		}
	}
	const onFinishFailed = (errorInfo: any) => {
		console.log('表单验证失败:', errorInfo)
	}
	return (
		<div className="login-container">
			<Card className="login-card" bordered={false}>
				<Form
					form={form}
					name="login"
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete="off"
					size="large"
				>
					<Form.Item
						name="email"
						rules={[
							{ required: true, message: '请输入登录账号!' },
							{ type: 'email', message: '请输入有效的邮箱地址!' }
						]}
					>
						<Input
							prefix={<UserOutlined />}
							placeholder='请输入登录账号'
							className="login-input"
						/>
					</Form.Item>

					<Form.Item
						name="password"
						rules={[
							{ required: true, message: '请输入登录密码!' },
							{ min: 6, message: '密码至少6个字符!' }
						]}
					>
						<Input.Password
							prefix={<LockOutlined />}
							placeholder='请输入登录的密码'
							className="login-input"
						/>
					</Form.Item>
					<Form.Item>
						<Button
							type="primary"
							htmlType="submit"
							loading={loading}
							className="login-button"
							block
						>
							{loading ? '登录中...' : '登录'}
						</Button>
					</Form.Item>
					<Form.Item className="login-links">
						<div className="links-container">
							<Button type="link" onClick={() => navigate('/register')} className="login-link">
								注册
							</Button>
							<Button type="link" className="login-link">
								忘记密码
							</Button>
						</div>
					</Form.Item>
				</Form>
			</Card>
		</div>
	)
}
export default Login